<template>
	<view class="container">
		<u-upload :action="action" :auto-upload="false" :file-list="fileList" @on-choose-complete="afterRead"
			@delete="deletePic" :max-count="1" name="file" :preview-full-image="true">
		</u-upload>
		<u-button @click="uploadBase64" type="primary" style="margin-top: 30rpx;">
			提交上传
		</u-button>
	</view>
	
</template>
<script>
	export default {
		data() {
			return {
				action: '', // 设置为空，因为我们不直接使用组件上传
				fileList: [],
				base64Data: '' // 存储转换后的Base64数据
			}
		},
		methods: {
			// 选择图片后的回调
			afterRead(event) {
				console.log('afterRead-1', event)
				const file = event[0]
				this.fileList = file // 更新文件列表
				console.log('afterRead', this.fileList)

				// 将图片转换为Base64
				this.getBase64(file.url).then(base64 => {
					this.base64Data = base64
				}).catch(err => {
					console.error('转换Base64失败:', err)
					uni.showToast({
						title: '图片处理失败',
						icon: 'none'
					})
				})
			},

			// 删除图片
			deletePic(event) {
				this.fileList = []
				this.base64Data = ''
			},

			// 将图片URL转换为Base64
			getBase64(fileUrl) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: fileUrl,
						encoding: 'base64',
						success: res => {
							// 添加Base64前缀（根据实际图片类型）
							let prefix = 'data:image/jpeg;base64,'
							if (fileUrl.indexOf('.png') !== -1) {
								prefix = 'data:image/png;base64,'
							} else if (fileUrl.indexOf('.gif') !== -1) {
								prefix = 'data:image/gif;base64,'
							}
							resolve(prefix + res.data)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},

			// 上传Base64数据到服务器
			uploadBase64() {
				console.log('upload:', this.base64Data)
				if (!this.base64Data) {
					uni.showToast({
						title: '请先选择图片',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '上传中...'
				})

				this.$u.api.uploadres({
					"usercode": "2636e646cb51b89a59c6d3150e245253",
					"rescode": this.base64Data,
					"restype": "0",
					"resdesc": "接单"
				}).then(res => {
					console.log('uploadres:',this.base64Data)

				})

				// 调用接口上传
				// this.$u.post('/api/res/uploadres', {
				// 	fileBase64: this.base64Data,
				// 	fileName: this.fileList[0].name || 'image.jpg'
				// }).then(res => {
				// 	uni.hideLoading()
				// 	uni.showToast({
				// 		title: '上传成功',
				// 		icon: 'success'
				// 	})
				// 	console.log('上传结果:', res)
				// }).catch(err => {
				// 	uni.hideLoading()
				// 	uni.showToast({
				// 		title: '上传失败',
				// 		icon: 'none'
				// 	})
				// 	console.error('上传错误:', err)
				// })
			}
		}
	}
</script>
<style lang="scss" scoped>
	.container {
		padding: 30rpx;
	}

	.upload-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 200rpx;
		height: 200rpx;
		background-color: #f7f7f7;
		border-radius: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #666;
		margin-top: 10rpx;
	}
</style>